from fastapi import APIRouter, Depends
from ..schemas.user import TokenResponse, RegisterResponse, LoginRequest, UserInfo
from ..services.user import *
from ..db import get_db

from .auth import create_access_token, get_current_user

user_router = APIRouter()


# 注册
@user_router.post("/register", response_model=RegisterResponse)
def register_user(user: RegisterRequest, db: Session = Depends(get_db)):
    # noinspection PyBroadException
    try:
        if create_user(db, user) is not None:
            return RegisterResponse(success=True, message="success")
        else:
            return RegisterResponse(success=False, message="email already exists")
    except Exception as e:
        return RegisterResponse(success=False, message=str(e))


# 登录
@user_router.post("/login", response_model=TokenResponse)
def login_user(user: LoginRequest, db: Session = Depends(get_db)):
    db_user = get_user_by_email(db, user.email)
    if db_user and verify_password(user.password, db_user.password_hash):
        access_token = create_access_token(data={"sub": db_user.email})
        return TokenResponse(access_token=access_token, token_type="bearer", message="success")
    return TokenResponse(message="username or password error")


# 获取用户信息
@user_router.get("/info")
def get_user_info(user: User = Depends(get_current_user)):
    return UserInfo(
        email=user.email,
        vip=user.vip,
        disk_quota=user.disk_quota,
        disk_usage=user.disk_used
    )

@user_router.get("/heartbeat")
def heartbeat(user: User = Depends(get_current_user)):
    return {"status": "ok"}